import React from "react";
import { Form, Input, Button, Checkbox, message } from "antd";
import { UserOutlined, LockOutlined } from "@ant-design/icons";
import "./Login.css";
import { loginApi } from "../../service/auth";
import { setToken, setUserName, setUserRole } from "../../utils/auth";

function Login(props) {
  const onFinish = (values) => {
    setUserName(values.username);
    loginApi({
      userName: values.username,
      userPwd: values.password,
    })
      .then((res) => {
        console.log(res);
        if (res.status === "200") {
          setToken(res.result.token);
          setUserRole(res.result.role);
          props.history.push("/admin/home");
        } else {
          message.info(res.msg);
        }
      })
      .catch((err) => {
        console.log(err);
        // message.err(err);
      });
  };
  return (
    <Form
      name="normal_login"
      className="login-form"
      initialValues={{
        remember: true,
      }}
      onFinish={onFinish}
    >
      <Form.Item
        name="username"
        rules={[
          {
            required: true,
            message: "请输入用户名!",
          },
        ]}
      >
        <Input
          prefix={<UserOutlined className="site-form-item-icon" />}
          placeholder="用户名"
        />
      </Form.Item>
      <Form.Item
        name="password"
        rules={[
          {
            required: true,
            message: "请输入密码!",
          },
          {
            pattern: new RegExp("^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,12}$"),
            message: "密码为包含英文和数字的6-12位字符！",
          },
        ]}
      >
        <Input
          prefix={<LockOutlined className="site-form-item-icon" />}
          type="password"
          placeholder="密码"
        />
      </Form.Item>
      <Form.Item>
        <Form.Item name="remember" valuePropName="checked" noStyle>
          <Checkbox>记住密码</Checkbox>
        </Form.Item>
        <a className="login-form-forgot" href="https://www.baidu.com">
          密码找回？
        </a>
      </Form.Item>

      <Form.Item>
        <Button type="primary" htmlType="submit" className="login-form-button">
          登录
        </Button>
        <Button
          type="primary"
          htmlType="submit"
          className="login-form-button"
          onClick={() => {
            props.history.push("/register");
          }}
        >
          注册
        </Button>
      </Form.Item>
    </Form>
  );
}

export default Login;
